package zucc.lcj.android_finalwork.help;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;

import zucc.lcj.android_finalwork.LoginActivity;
import zucc.lcj.android_finalwork.MyDatabaseHelper;
import zucc.lcj.android_finalwork.R;

public class HelpAddActivity extends AppCompatActivity {
    Button back,add;
    ImageView imageView;
    ImageButton choose_photo;
    View bk;
    EditText title,content;
    String titles,contents;//存入数据库
    String time;//存入数据库

    private MyDatabaseHelper dbHelper;

    public static final int TAKE_CAMERA = 101;
    public static final int PICK_PHOTO = 102;
    private Uri imageUri;
    private String imageurl;//存入数据库
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_help_add);
        dbHelper = new MyDatabaseHelper(this,"UserStore.db",null,1);

        //取消返回
        back = (Button) findViewById(R.id.help_add_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(HelpAddActivity.this, HelpActivity.class);
                startActivity(intent);
            }
        });
        title = (EditText) findViewById(R.id.help_add_title) ;
        content = (EditText) findViewById(R.id.help_add_content) ;
        //确认发表 导入数据库（标题、内容、照片）
        add = (Button) findViewById(R.id.help_add_send);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                titles=title.getText().toString();
                contents=content.getText().toString();
                //获取当前时间
                SimpleDateFormat formatter = new SimpleDateFormat ("yyyy年MM月dd日");
                Date curDate = new Date(System.currentTimeMillis());
                time = formatter.format(curDate);
                System.out.println("时间"+time);

                SQLiteDatabase db = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("help_title", titles);
                values.put("help_content", contents);
                values.put("help_state","未完成");
                values.put("help_photo", imageurl);
                values.put("help_userPost", LoginActivity.global_login_user_id);
                values.put("help_userHelp",0);
                values.put("help_time",time);
                db.insert("Help", null, values);
                values.clear();

                db.execSQL("update UserInfo set helpPost=helpPost+1 where UserInfo.user_name=?",new String[]{LoginActivity.global_login_user});

                Toast.makeText(getApplicationContext(), "发表成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.setClass(HelpAddActivity.this, HelpActivity.class);
                startActivity(intent);
            }
        });

        //从相册选择图片
        bk = (View) findViewById(R.id.help_add_addimgsbk);
        imageView = (ImageView) findViewById(R.id.help_add_img);
        choose_photo = (ImageButton) findViewById(R.id.help_add_addimg) ;
        choose_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //动态申请获取访问 读写磁盘的权限
                if (ContextCompat.checkSelfPermission(HelpAddActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(HelpAddActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
                } else {
                    //打开相册
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    //Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
                    intent.setType("image/*");
                    startActivityForResult(intent, PICK_PHOTO); // 打开相册
                }
            }
        });



    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_CAMERA:
                if (resultCode == RESULT_OK) {
                    try {
                        // 将拍摄的照片显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        imageView.setImageBitmap(bitmap);

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case PICK_PHOTO:
                if (resultCode == RESULT_OK) { // 判断手机系统版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        // 4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    } else {
                        // 4.4以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data);
                    }
                }

                break;
            default:
                break;
        }
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        // 根据图片路径显示图片
        displayImage(imagePath);
        imageurl=imagePath;
    }

    /**
     * android 4.4以前的处理方式
     * @param data
     */
    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    @SuppressLint("Range")
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            bk.setVisibility(View.INVISIBLE);
            choose_photo.setVisibility(View.INVISIBLE);
            imageView.setImageBitmap(bitmap);
            imageView.setVisibility(View.VISIBLE);
        } else {
            Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show();
        }
    }
}